<template>
  <form @submit.prevent="handleLogin" class="space-y-4">
    <div>
      <label class="block text-sm font-medium text-gray-700 mb-1">
        用户名
      </label>
      <input
        v-model="loginForm.username"
        type="text"
        maxlength="8"
        :class="[
          'w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-bsr focus:border-transparent outline-none transition-all',
          fieldErrors.username ? 'border-red-500' : 'border-gray-300',
        ]"
        placeholder="请输入用户名（最多8位）"
        @input="clearFieldError('username')"
      />
      <p v-if="fieldErrors.username" class="mt-1 text-sm text-red-600">
        {{ fieldErrors.username }}
      </p>
    </div>
    <div>
      <label class="block text-sm font-medium text-gray-700 mb-1"> 密码 </label>
      <input
        v-model="loginForm.password"
        type="password"
        maxlength="16"
        :class="[
          'w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-bsr focus:border-transparent outline-none transition-all',
          fieldErrors.password ? 'border-red-500' : 'border-gray-300',
        ]"
        placeholder="请输入密码"
        @input="clearFieldError('password')"
      />
      <p v-if="fieldErrors.password" class="mt-1 text-sm text-red-600">
        {{ fieldErrors.password }}
      </p>
    </div>
    <div>
      <!-- <label class="block text-sm font-medium text-gray-700 mb-1">验证码</label> -->

      <!-- 验证码图片显示区域 -->
      <!-- <div v-if="captchaImage" class="mb-3">
        <div class="flex items-center space-x-3">
          <div class="w-full">
            <img 
              :src="captchaImage" 
              alt="验证码" 
              class="h-20 object-contain border border-gray-300 rounded-lg bg-gray-50"
              @click="$emit('refresh-captcha')"
            />
          </div>
        </div>
        <p class="mt-1 text-xs text-gray-500">点击图片可刷新验证码</p>
      </div> -->

      <!-- 验证码输入框 -->
      <!-- <div class="flex items-center">
        <div class="flex-1">
          <input
            v-model="loginForm.code"
            type="text"
            maxlength="4"
            :class="[
              'w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-bsr focus:border-transparent outline-none transition-all',
              fieldErrors.code ? 'border-red-500' : 'border-gray-300'
            ]"
            placeholder="输入上方验证码"
            @input="handleCodeInput($event)"
          />
          <p v-if="fieldErrors.code" class="mt-1 text-sm text-red-600">
            {{ fieldErrors.code }}
          </p>
        </div>
        <button
          v-if="!captchaImage"
          type="button"
          @click="$emit('send-code', loginForm.username)"
          :disabled="!loginForm.username"
          class="ml-3 px-3 py-2 bg-bsr text-white rounded-lg disabled:opacity-50"
        >
          <span>获取验证码</span>
        </button>
      </div> -->
    </div>

    <div
      v-if="errorMessage"
      class="text-red-600 text-sm text-center bg-red-50 p-2 rounded"
    >
      {{ errorMessage }}
    </div>

    <button
      type="submit"
      :disabled="loading"
      class="w-full bg-bsr text-white py-3 rounded-lg font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
    >
      <span v-if="!loading">登录</span>
      <span v-else class="flex items-center justify-center">
        <svg
          class="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
        >
          <circle
            class="opacity-25"
            cx="12"
            cy="12"
            r="10"
            stroke="currentColor"
            stroke-width="4"
          ></circle>
          <path
            class="opacity-75"
            fill="currentColor"
            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
          ></path>
        </svg>
        登录中...
      </span>
    </button>
  </form>
</template>

<script setup lang="ts">
interface Props {
  loading?: boolean;
  errorMessage?: string;
  captchaImage?: string;
}

interface Emits {
  (e: "send-code", username: string): void;
  (e: "refresh-captcha"): void;
  (
    e: "login",
    data: { username: string; password: string; code: string }
  ): void;
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  errorMessage: "",
  captchaImage: "",
});

const emit = defineEmits<Emits>();

// const { login } = useAuth()

// 登录表单
const loginForm = reactive({
  username: "",
  password: "",
  code: "",
});

// 字段验证错误
const fieldErrors = reactive({
  username: "",
  password: "",
  code: "",
});

// 验证函数
const validateField = (
  fieldName: "username" | "password" | "code",
  value: string
) => {
  // 检查是否为空
  if (!value || value.trim() === "") {
    const fieldNameMap: Record<string, string> = {
      username: "用户名",
      password: "密码",
      code: "验证码",
    };
    fieldErrors[fieldName] = `请填写${fieldNameMap[fieldName]}`;
    return false;
  }

  // 检查长度限制
  switch (fieldName) {
    case "username":
      if (value.length > 8) {
        fieldErrors[fieldName] = "用户名长度不能超过 8位";
        return false;
      }
      // 检查用户名格式：仅能使用数字、字母、"_"及"-"
      if (!/^[a-zA-Z0-9_-]+$/.test(value)) {
        fieldErrors[fieldName] = '用户名仅能使用数字、字母、"_"及"-"';
        return false;
      }
      // 检查不能为纯数字
      if (/^\d+$/.test(value)) {
        fieldErrors[fieldName] = "用户名不能为纯数字";
        return false;
      }
      break;
    case "password":
      if (value.length < 8) {
        fieldErrors[fieldName] = "密码长度必须至少8位";
        return false;
      }
      if (value.length > 16) {
        fieldErrors[fieldName] = "密码长度不能超过16位";
        return false;
      }
      
      // 检查密码复杂度：必须包含字母、数字、特殊符号中的至少两种
      const hasLetter = /[a-zA-Z]/.test(value);
      const hasNumber = /[0-9]/.test(value);
      const hasSpecial = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value);
      
      const categoryCount = [hasLetter, hasNumber, hasSpecial].filter(Boolean).length;
      
      if (categoryCount < 2) {
        fieldErrors[fieldName] = "密码必须包含字母、数字、特殊符号中的至少两种";
        return false;
      }
      break;
  }

  fieldErrors[fieldName] = "";
  return true;
};

// 实时清除错误
const clearFieldError = (fieldName: "username" | "password" | "code") => {
  fieldErrors[fieldName] = "";
};

// 处理验证码输入，只允许字母和数字
const handleCodeInput = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const value = target.value;

  // 只保留字母和数字
  const alphanumericValue = value.replace(/[^a-zA-Z0-9]/g, "");

  // 更新表单值
  loginForm.code = alphanumericValue;

  // 清除错误
  clearFieldError("code");
};

const validateLoginForm = () => {
  let isValid = true;
  isValid = validateField("username", loginForm.username) && isValid;
  isValid = validateField("password", loginForm.password) && isValid;
  // isValid = validateField('code', loginForm.code) && isValid
  return isValid;
};

// 处理登录
const handleLogin = async () => {
  // 验证表单
  if (!validateLoginForm()) {
    return;
  }

  emit("login", {
    username: loginForm.username,
    password: loginForm.password,
    code: loginForm.code,
  });
};

// 暴露方法给父组件
defineExpose({
  resetForm: () => {
    loginForm.username = "";
    loginForm.password = "";
    loginForm.code = "";
    fieldErrors.username = "";
    fieldErrors.password = "";
    fieldErrors.code = "";
  },
  loginForm, // 暴露表单数据给父组件
});
</script>

<style scoped>
/* 输入框焦点效果 */
input:focus {
  box-shadow: 0 0 0 3px rgba(194, 48, 28, 0.1);
}

/* 按钮悬停效果 */
button {
  transition: all 0.2s ease;
}
</style>
